import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {FooterToolbar, PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import type {SortOrder} from 'antd/es/table/interface';
import {
  addInterfaceInfo,
  deleteInterfaceInfo,
  listInterfaceInfoVoByPage,
  offlineInterfaceInfo,
  onlineInterfaceInfo,
  updateInterfaceInfo
} from '@/services/CloudBridge-Service/interfaceInfoController';
import CreateModal from '@/pages/Admin/InterfaceInfo/components/CreateModal';
import UpdateModal from "@/pages/Admin/InterfaceInfo/components/UpdateModal";
import {download, upload} from "@/services/CloudBridge-Service/fileController";
import {addSdkInfo} from "@/services/CloudBridge-Service/sdkInfoController";

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfoVO>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfoVO[]>([]);
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    const hide = message.loading('正在添加');
    try {
      const {file, ...rest} = fields

      // 创建 FormData 对象
      const formData = new FormData();
      // 添加文件，这里的 'file' 要和后端的 @RequestParam("file") 对应
      formData.append('file', file[0].originFileObj || file[0]);
      const fileName = file[0].name

      const res: any = await upload(formData);
      let sdkPath = '';
      if (res.data) {
        sdkPath = res.data;
      }
      const sdkInfoAddRequest: API.SdkInfoAddRequest = {
        name: fileName,
        path: sdkPath
      }
      const res2: any = await addSdkInfo(sdkInfoAddRequest)
      let sdkId = ''
      if (res2.data) {
        sdkId = res2.data
      }

      await addInterfaceInfo({
        ...rest,
        sdkId: sdkId
      });
      hide();
      message.success('创建成功');
      handleModalVisible(false);
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败，' + error.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfoVO[]) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改中');
    try {
      await updateInterfaceInfo({
        id: currentRow.id,
        ...fields
      });
      hide();
      message.success('操作成功');
      return true;
    } catch (error: any) {
      hide();
      message.error('操作失败，' + error.message);
      return false;
    }
  };

  /**
   * 发布接口
   *
   * @param record
   */
  const handleOnline = async (record: API.IdRequest) => {
    const hide = message.loading('发布中');
    if (!record) return true;
    try {
      await onlineInterfaceInfo({
        id: record.id
      });
      hide();
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('操作失败，' + error.message);
      return false;
    }
  };

  /**
   * 下线接口
   *
   * @param record
   */
  const handleOffline = async (record: API.IdRequest) => {
    const hide = message.loading('发布中');
    if (!record) return true;
    try {
      await offlineInterfaceInfo({
        id: record.id
      });
      hide();
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('操作失败，' + error.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param record
   */
  const handleRemove = async (record: API.InterfaceInfoVO[]) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      // 循环删除
      for (let i = 0; i < record.length; i++) {
        await deleteInterfaceInfo({
          id: record[i].id
        });
      }
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 下载节点的SDK
   * @param record
   */
  const handleDownload = async (record: API.InterfaceInfoVO) => {
    const hide = message.loading('正在下载');
    if (!record?.sdkId) {
      hide();
      message.error('下载参数错误');
      return false;
    }

    try {
      const response = await download({sdkId: String(record.sdkId)});

      // 确保响应是 Blob 类型
      if (!(response instanceof Blob)) {
        throw new Error('响应格式错误');
      }

      // 从响应头获取文件名（如果有的话）
      const fileName = record.name || 'download.zip'; // 使用默认文件名作为后备

      // 创建下载链接
      const url = window.URL.createObjectURL(response);
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.download = fileName + ".zip";

      // 添加到文档并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      hide();
      message.success('下载成功');
      return true;
    } catch (error: any) {
      console.error('Download error:', error);
      hide();
      message.error('下载失败：' + (error.message || '未知错误'));
      return false;
    }
  }


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.InterfaceInfoVO>[] = [
    {
      title: '接口编号',
      key: 'id',
      width: 75,
      dataIndex: 'id',
      valueType: 'text',
    },
    {
      title: '接口名称',
      key: 'name',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
        }]
      }
    },
    {
      title: '描述',
      key: 'description',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '请求方法',
      key: 'method',
      dataIndex: 'method',
      valueType: 'text',
    },
    {
      title: 'url',
      key: 'url',
      dataIndex: 'url',
      valueType: 'text',
    },
    {
      title: '请求参数',
      key: 'requestParams',
      dataIndex: 'requestParams',
      valueType: 'jsonCode',
    },
    {
      title: '请求头',
      key: 'requestHeader',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
    },
    {
      title: '响应头',
      key: 'responseHeader',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
    },
    {
      title: '状态',
      key: 'status',
      fixed: 'right',
      width: 60,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record) => [
        <Button
          key="modify"
          color="default"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        <Button
          key="download"
          onClick={() => {
            handleDownload(record);
          }}
        >
          下载SDK
        </Button>,
        record.status === 0 ? <Button
          key="publish"
          onClick={() => {
            handleOnline(record);
          }}
        >
          发布
        </Button> : null,
        record.status === 1 ?
          <Button
            key="offline"
            danger
            onClick={() => {
              handleOffline(record);
            }}
          >
            下线
          </Button> : null,
        <Button
          key="delete"
          danger
          onClick={() => {
            const interfaceTable: API.InterfaceInfoVO[] = [];
            interfaceTable.push(record)
            handleRemove(interfaceTable);
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 'max-content', y: 'max-content'}} // 横纵向overflowhidden
        bordered // 堆叠多列
        pagination={{defaultPageSize: 5}} // 分页
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={
          async (
            params,
            sort: Record<string, SortOrder>,
            filter: Record<string, React.ReactText[] | null>,
          ) => {
            const res: any = await listInterfaceInfoVoByPage({
              ...params,
            });
            console.log(res)
            if (res?.data) {
              return {
                data: res?.data.records || [],
                success: true,
                total: res?.data.total || 0,
              };
            } else {
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalVisible(false);
        }}
        onSubmit={(values) => {
          handleAdd(values);
        }}
        visible={createModalVisible}
      />
    </PageContainer>
  );
};
export default TableList;
